/**
 * @file myADS1115.h
 * @brief 用于ADS1115的库
 * @version 1.0
 * @date 2024-03-25
 * @author  Neo
 *
 * 状态：已在FreeRTOS中使用单独任务测试完成
 *
 * 该库是对robtillaart/ADS1X15@^0.4.2的二次封装
 * 该库是基于ADS1115的I2C模数转换器库，可以通过I2C读取4个模拟信号
 * 该库的使用需要先初始化I2C，然后初始化ADS1115，设置增益，然后就可以通过读写函数读取模拟信号
 * 使用说明：
 * 1. 首先需要初始化I2C，然后初始化ADS1115
 * 2. 设置增益，然后通过读写函数读取模拟信号
 *
 */

#ifndef _my_ADS1115_H_
#define _my_ADS1115_H_

#include <Arduino.h>
#include <Adafruit_ADS1X15.h>
#include "myShowMsg.h"
#include "IO_Config.h"
// 定义ADS1115的I2C地址,默认地址为0x48
Adafruit_ADS1115 ads; /* Use this for the 16-bit version */

bool InitializeADS1115()
{
    // Wire.setSDA(PB9);   // 设置I2C的SDA和SCL引脚
    // Wire.setSCL(PB8);   // 设置I2C的SDA和SCL引脚
    // Wire.begin();       // 初始化Wire库
    //                                                                ADS1015  ADS1115
    //                                                                -------  -------
    // ads.setGain(GAIN_TWOTHIRDS);  // 2/3x gain +/- 6.144V  1 bit = 3mV      0.1875mV (default)
    ads.setGain(GAIN_ONE); // 1x gain   +/- 4.096V  1 bit = 2mV      0.125mV
    // ads.setGain(GAIN_TWO);        // 2x gain   +/- 2.048V  1 bit = 1mV      0.0625mV
    // ads.setGain(GAIN_FOUR);       // 4x gain   +/- 1.024V  1 bit = 0.5mV    0.03125mV
    // ads.setGain(GAIN_EIGHT);      // 8x gain   +/- 0.512V  1 bit = 0.25mV   0.015625mV
    // ads.setGain(GAIN_SIXTEEN);    // 16x gain  +/- 0.256V  1 bit = 0.125mV  0.0078125mV
    if (!ads.begin())
    {
        return false;
    }
    // ads.startADCReading(ADS1X15_REG_CONFIG_MUX_DIFF_0_1, /*continuous=*/true);
    return true;
}

float ReadADS1115(uint8_t channel)
{
    if (channel >= 4)
        return 0;
    int16_t adc;
    float volts;
    adc = ads.readADC_SingleEnded(channel);
    volts = ads.computeVolts(adc);
    ShowMsg("A" + String(channel) + ":" + String(adc) + "\t" + String(volts), true);
    return volts;
}

void ReadADS1115All()
{

    int16_t adc0, adc1, adc2, adc3;
    float volts0, volts1, volts2, volts3;

    adc0 = ads.readADC_SingleEnded(0);
    adc1 = ads.readADC_SingleEnded(1);
    adc2 = ads.readADC_SingleEnded(2);
    adc3 = ads.readADC_SingleEnded(3);
    myAI.AI0 = adc0;
    myAI.AI1 = adc1;
    myAI.AI2 = adc2;
    myAI.AI3 = adc3;
    volts0 = ads.computeVolts(adc0);
    volts1 = ads.computeVolts(adc1);
    volts2 = ads.computeVolts(adc2);
    volts3 = ads.computeVolts(adc3);
    ShowMsg("Read ADS1115:");
    ShowMsg("\nA0:\t" + String(adc0) + "\t" + String(volts0, 3) + "V");
    ShowMsg("\nA1:\t" + String(adc1) + "\t" + String(volts1, 3) + "V");
    ShowMsg("\nA2:\t" + String(adc2) + "\t" + String(volts2, 3) + "V");
    ShowMsg("\nA3:\t" + String(adc3) + "\t" + String(volts3, 3) + "V", true);
}

#endif